package dao

import (
	"database/sql"
	"go_payment/model"
)

func AddOrder(order *model.Order) (int64, error) {
	sql := "INSERT INTO pay_order(pay_memberid,pay_orderid,pay_amount,pay_poundage,pay_preamount,`pay_actualamount`,`pay_applydate`,`pay_bankcode`,`pay_bankname`,`pay_notifyurl`,`pay_callbackurl`,`pay_status`,`pay_tongdao`,`pay_tongdao_zh`,`pay_tjurl`,`pay_productname`,`pay_productnum`,`pay_productdesc`,`pay_producturl`,`attach`,`out_trade_id`,`ddlx`,`memberid`,`key`,`appid`,`appsecret`) VALUES(?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?)"
	stmt, err := db.Prepare(sql)
	defer stmt.Close()

	if err != nil {
		return 0, err
	}
	af, err := stmt.Exec(order.MchId, order.OrderId, order.Amount, order.Poundage, order.PreAmount, order.ActualAmount, order.ApplyDate, order.BankCode, "", order.NotifyUrl, order.CallBackUrl, order.Status, order.TongDao, order.TongDaoZh, "", order.ProductName, order.ProductNum, order.ProductDesc, order.ProductUrl, order.Attach, order.OutTradeId, order.Ddlx, order.MemberId, order.Key, order.AppId, order.AppSecret)
	if err != nil {
		return 0, err
	}
	id, err := af.LastInsertId()
	if err != nil {
		return 0, err
	}
	return id, nil
}

func GetOrder(orderSn string) model.Order {
	s := `SELECT pay_memberid,pay_orderid,pay_amount,pay_notifyurl,pay_status FROM pay_order WHERE pay_orderid=? LIMIT 1`
	stmt, err := db.Prepare(s)
	if err != nil {
		panic(err)
	}
	defer stmt.Close()
	row := stmt.QueryRow(orderSn)
	var _order model.Order
	err = row.Scan(&_order.MemberId, &_order.OrderId, &_order.Amount, &_order.NotifyUrl, &_order.Status)
	if err != nil && err != sql.ErrNoRows {
		panic(err)
	}
	return _order
}
